<template>
  <div>
    <el-button @click="sendMsg">发送消息</el-button>
    <el-button @click="stopMsg">中断发送</el-button>
    <p v-for="(item, index) in msgList" :key="index">{{ item }}</p>
  </div>

</template>
<script>
export default {
  name: 'admin',
  data() {
    return {
      msgList: [],
      eventSource: null,
    }
  },
  methods: {
    sendMsg() {
      let vm = this

      //方案1:EventSource
      const eventSource = new EventSource('http://localhost:8002/events');
      this.eventSource = eventSource
      //消息监听
      eventSource.onmessage = function (event) {
        console.log(eventSource, vm, '状态')
        console.log(event.data); // 输出SSE发送的数据  
        if (event.data === 'end') {
          eventSource.close()
        } else {
          vm.msgList.push(event.data)
        }

      };
      //连接成功
      eventSource.onopen = function (event) {

      }
      //连接出错
      eventSource.onerror = function (error) {
        if (eventSource.readyState === EventSource.CLOSED) {
          // 连接已关闭，可能需要重新连接  
          console.error('SSE连接已关闭:', error);
        }
      }

      //方案2:xhr(不推荐)
      // const xhr = new XMLHttpRequest(); 
      // const url = '/sse/events'; 
      // xhr.open('GET', url,true); 
      // xhr.setRequestHeader('Accept', 'text/event-stream');

      // xhr.onload = (event)=>{
      //   if(xhr.status === 200){
      //     console.log(xhr.responseText,'onload',event)
      //   }
      // }

      // xhr.onreadystatechange = (event)=>{
      //   // if(xhr.status === 200){
      //   //   console.log(xhr.responseText,'onreadystatechange',event)
      //   // }

      // }
      // xhr.onprogress = (event)=>{
      //   if(xhr.status === 200){
      //     console.log(xhr.responseText,'onreadystatechange',event)

      //   }
      // }
      // xhr.send()
    },
    stopMsg() {
      this.eventSource.onclose = function (event) {
        console.log("e", event);

      }
    }
  }
}
</script>
<style lang="less"></style>
